package com.auoem.radio.ui.radio;

import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.UiThread;

import com.auctus.am.developer.AuHelper;
import com.auctus.am.framework.entity.ChannelInf;
import com.auctus.am.framework.entity.EqualizerInf;
import com.auctus.am.framework.entity.RadioBaseInf;
import com.auctus.am.framework.enums.ApiStatusEnum;
import com.auctus.am.framework.enums.Power;
import com.auctus.am.framework.imp.HlThreadPoolManager;
import com.auctus.am.framework.imp.RadioManager;
import com.auctus.am.framework.interfaces.ApiCallback;
import com.auctus.am.framework.interfaces.IApi;
import com.auctus.am.framework.picker.IIntPickDataWrap;
import com.auctus.am.framework.picker.RadioPickData;
import com.auctus.am.framework.utils.LogM;
import com.auctus.am.framework.utils.SPUtils;
import com.auoem.radio.R;
import com.auoem.radio.base.BaseFragment;
import com.auoem.radio.base.OemApplication;
import com.auoem.radio.common.custview.ConfirmDialogFragment;
import com.auoem.radio.common.custview.EditDialogFragment;
import com.auoem.radio.common.custview.wheel.SimplePickerDialog;
import com.auoem.radio.common.utils.ResourceUtils;
import com.auoem.radio.common.utils.ToastUtils;
import com.auoem.radio.databinding.FragmentRadioBinding;
import com.auoem.radio.ui.other.TestCmdActivity;
import com.auoem.radio.ui.other.TestDbActivity;

import java.io.IOException;

/**
 * 20240417  切换成功，重新开喇叭
 *
 *
 */
public class RadioFragment extends BaseFragment {

    private static final String TAG = "RadioFragment";

    private FragmentRadioBinding mBinding;

    private RadioBaseInf radioBaseInf;

    private IIntPickDataWrap pickDataTail, pickDataTot;
    private SimplePickerDialog mSelectDialog;
    private EditDialogFragment mEditDialog;
    private ConfirmDialogFragment mConfirmDialog;
    private IApi mApi;

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        mBinding = FragmentRadioBinding.inflate(inflater);
        initData();
        updateView();
        updateVer();
        return mBinding.getRoot();
    }


    @Override
    public void onResume() {
        super.onResume();
    }

    private void initData() {
        mApi = AuHelper.getInstance().getApi();
        radioBaseInf = RadioManager.getInstance().getRadioData().getRadioBaseInf();
        pickDataTail = RadioPickData.getInstance().getRadioTail();
        pickDataTot = RadioPickData.getInstance().getRadioTot();
    }


    @Override
    public void onClick(View v) {
        LogM.d(TAG, "onClick Radio");
        if (v == mBinding.cbSaveV) {
            setSaveLv();
        } else if (v == mBinding.cbEqualizerV) {
            setPowerEqualizer();
        } else if (v == mBinding.tvTailV) {
            selTail();
        } else if (v == mBinding.cbPowerV) {
            setPowerLv();
        } else if (v == mBinding.tvTotV) {
            selTot();
        } else if (v == mBinding.tvCtV) {
            Intent intent = new Intent(getActivity(), CtListActivity.class);
            startActivity(intent);
        } else if (v == mBinding.tvClsV) {
            showCleanConfirm();
        } else if (v == mBinding.tvClsK) {
            //todo 测试页面
            Intent intent = new Intent(getActivity(), TestCmdActivity.class);
            startActivity(intent);
        } else if (v == mBinding.tvIndIdV) {
            editIndId();
        } else if (v == mBinding.tvVersionV) {
//            AuHelper.getInstance().getApi().getModuleVer(new ApiCallback<String>() {
//                @Override
//                public void onResponse(ApiStatusEnum status, String result, String msg) {
//                    LogM.d(TAG, "getModuleVer: " + result);
//                }
//            });
        } else if (v == mBinding.tvTalk) {
            Intent intent = new Intent(getActivity(), TestDbActivity.class);
            startActivity(intent);
        } else if (v == mBinding.cbAudio) {
            enableSysAudio();
        }
    }

    private void setSaveLv() {
        showProgress(R.string.am_common_exe_ing);
        int saveLv = mBinding.cbSaveV.isChecked() ? 1 : 0;
        //模拟信道省电
        ChannelInf curCh = RadioManager.getInstance().getRadioData().getCurChannel();
        if (curCh == null) {
            return;
        }
        if (curCh.isDigModel) {
            mApi.setDigPwSave(saveLv == 1, 240, true, new ApiCallback() {
                @Override
                public void onResponse(ApiStatusEnum status, Object result, String msg) {
                    doOnSetPowerSave(status, saveLv);
                }
            });
        } else {
            mApi.setPowerSave(saveLv == 1 ? 4 : 0, true, new ApiCallback() {
                @Override
                public void onResponse(ApiStatusEnum status, Object result, String msg) {
                    doOnSetPowerSave(status, saveLv);
                }
            });
        }
    }

    private void doOnSetPowerSave(ApiStatusEnum status, int saveLv) {
        toastResultUI(status);
        if (status == ApiStatusEnum.SUCCESS) {
            ToastUtils.showShortToast(getActivity(), R.string.am_common_exe_success);
            radioBaseInf.powerSaveLv = saveLv;
            saveEditData();
        } else {
            updateBind();
        }
    }

    private void setPowerLv() {
        showProgress(R.string.am_common_exe_ing);
        int saveLv = mBinding.cbPowerV.isChecked() ? 1 : 0;
        mApi.setPower(saveLv == 1 ? Power.HEIGHT : Power.LOW, true, new ApiCallback() {
            @Override
            public void onResponse(ApiStatusEnum status, Object result, String msg) {
                toastResultUI(status);
                if (status == ApiStatusEnum.SUCCESS) {
                    ToastUtils.showShortToast(getActivity(), R.string.am_common_exe_success);
                    radioBaseInf.powerLv = saveLv;
                    saveEditData();

                    //切换成功，重新开喇叭
                    try {
                        OemApplication.getApplication().getDevCtrlHorn2().PowerOnDevice();
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                } else {
                    updateBind();
                }
            }
        });
    }

    private void setPowerEqualizer() {
        int saveLv = mBinding.cbEqualizerV.isChecked() ? 1 : 0;
        EqualizerInf equalizerInf = new EqualizerInf();
        equalizerInf.setCst(mBinding.cbEqualizerV.isChecked());
        showProgress(R.string.am_common_exe_ing);
        mApi.setEqualizer(equalizerInf, true, new ApiCallback() {
            @Override
            public void onResponse(ApiStatusEnum status, Object result, String msg) {
                toastResultUI(status);
                if (status == ApiStatusEnum.SUCCESS) {
                    ToastUtils.showShortToast(getActivity(), R.string.am_common_exe_success);
                    radioBaseInf.equalizerLv = saveLv;
                    saveEditData();
                } else {
                    updateBind();
                }
            }
        });
    }

    private void selTail() {
        showSingleSelect(pickDataTail, new SimplePickerDialog.OnPickListener() {
            @Override
            public void onPicked(int sel1, int v1) {
                setTail(v1);
            }
        });
    }

    private void setTail(int v1) {
        showProgress(R.string.am_common_exe_ing);
        mApi.setTailFreq(v1, true, new ApiCallback() {
            @Override
            public void onResponse(ApiStatusEnum status, Object result, String msg) {
                toastResultUI(status);
                if (status == ApiStatusEnum.SUCCESS) {
                    radioBaseInf.tail = v1;
                    saveEditData();
                }
                updateTail();
            }
        });
    }

    private void selTot() {
        showSingleSelect(pickDataTot, new SimplePickerDialog.OnPickListener() {
            @Override
            public void onPicked(int sel1, int v1) {
                setTot(v1);
            }
        });
    }

    private void setTot(int v1) {
        showProgress(R.string.am_common_exe_ing);
        mApi.setTot(v1, true, new ApiCallback() {
            @Override
            public void onResponse(ApiStatusEnum status, Object result, String msg) {
                toastResultUI(status);
                if (status == ApiStatusEnum.SUCCESS) {
                    radioBaseInf.tot = v1;
                    saveEditData();
                }
                updateBind();
            }
        });
    }

    private void editGrpId() {
        if (mEditDialog == null) {
            mEditDialog = new EditDialogFragment();
        }
        mEditDialog.setOnEditFinishListener(new EditDialogFragment.OnEditFinishListener() {
            @Override
            public void onFinished(String content) {
                try {
                    int id = Integer.parseInt(content.trim());
                    if (id <= 0) {
                        ToastUtils.showShortToast(getActivity(), R.string.am_common_input_invalid);
                        return;
                    }
                    setGrpId(id);
                } catch (NumberFormatException e) {
                    e.printStackTrace();
                }
            }
        });
//        mEditDialog.setInputType(InputType.TYPE_CLASS_TEXT);//todo 大部分使用普通字符
//        mEditDialog.setLines(lines);
        if (!mEditDialog.isAdded() && null == getActivity().getSupportFragmentManager().findFragmentByTag("editGrpDialog")) {
            mEditDialog.showNow(getActivity().getSupportFragmentManager(), "editGrpDialog");
        }
        mEditDialog.setContent(ResourceUtils.getResourcesString(R.string.hl_radio_grp_id_hint), radioBaseInf.grpId + "");
        mEditDialog.setAttr(7, "");
    }

    private void setGrpId(int grpId) {
        showProgress(R.string.am_common_exe_ing);
        mApi.setGroupId(grpId, new ApiCallback() {
            @Override
            public void onResponse(ApiStatusEnum status, Object result, String msg) {
                toastResultUI(status);
                if (status == ApiStatusEnum.SUCCESS) {
                    radioBaseInf.grpId = grpId;
                    saveEditData();
                }
                updateBind();
            }
        });
    }

    private void editIndId() {
        if (mEditDialog == null) {
            mEditDialog = new EditDialogFragment();
        }
        mEditDialog.setOnEditFinishListener(new EditDialogFragment.OnEditFinishListener() {
            @Override
            public void onFinished(String content) {
                try {
                    int id = Integer.parseInt(content.trim());
                    if (id <= 0 || id > 16776415) {
                        ToastUtils.showShortToast(getActivity(), R.string.hl_radio_toast_invalid_ind_id);
                        return;
                    }
                    setIndId(id);
                } catch (NumberFormatException e) {
                    ToastUtils.showShortToast(getActivity(), R.string.hl_radio_toast_invalid_ind_id);
                    e.printStackTrace();
                }
            }
        });
//        mEditDialog.setInputType(InputType.TYPE_CLASS_TEXT);//todo 大部分使用普通字符
//        mEditDialog.setLines(lines);
        if (!mEditDialog.isAdded() && null == getActivity().getSupportFragmentManager().findFragmentByTag("editGrpDialog")) {
            mEditDialog.showNow(getActivity().getSupportFragmentManager(), "editGrpDialog");
        }
        mEditDialog.setContent(ResourceUtils.getResourcesString(R.string.hl_radio_grp_id_hint), radioBaseInf.indId + "");
        mEditDialog.setAttr(8, "");
    }

    private void setIndId(int indId) {
        showProgress(R.string.am_common_exe_ing);
        mApi.setWlkId(indId, true, new ApiCallback() {
            @Override
            public void onResponse(ApiStatusEnum status, Object result, String msg) {
                toastResultUI(status);
                if (status == ApiStatusEnum.SUCCESS) {
                    radioBaseInf.indId = indId;
                    saveEditData();
                }
                updateBind();
            }
        });
    }

    private void cls() {
//        RadioManager.getInstance().cls();
        RadioManager.getInstance().getRadioData().cls();
    }

    private void updateView() {
        updateBind();
        updateTail();
    }

    @UiThread
    private void updateBind() {
        try {
            requireActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    mBinding.setRadioInf(radioBaseInf);
                }
            });
        } catch (IllegalStateException e) {
            System.out.println("requireActivity illegal");
        }
    }

    @UiThread
    private void updateTail() {
        try {
            requireActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    String txtTail = pickDataTail.getDispOnValue(radioBaseInf.tail);
                    mBinding.tvTailV.setText(txtTail);
                }
            });
        } catch (IllegalStateException e) {
            System.out.println("requireActivity illegal");
        }
    }

    public void showSingleSelect(IIntPickDataWrap intPickDataWrap, SimplePickerDialog.OnPickListener onPickListener) {
        if (mSelectDialog == null) {
            mSelectDialog = new SimplePickerDialog(getActivity(), intPickDataWrap, 0, onPickListener, null);
        } else {
            mSelectDialog.update(intPickDataWrap, SimplePickerDialog.INVALID, onPickListener, null);
        }
        mSelectDialog.show();
    }

    private void showCleanConfirm() {
        if (mConfirmDialog == null) {
            mConfirmDialog = new ConfirmDialogFragment();
        }
        mConfirmDialog.setOnConfirmListener(new ConfirmDialogFragment.OnConfirmListener() {
            @Override
            public void onConfirm(boolean isOk) {
                if (isOk) {
                    clsExit();
                }
            }
        });
        if (!mConfirmDialog.isAdded() && null == getActivity().getSupportFragmentManager().findFragmentByTag("confirmClsDialog")) {
            mConfirmDialog.showNow(getActivity().getSupportFragmentManager(), "confirmClsDialog");
        }
        mConfirmDialog.setContent(ResourceUtils.getResourcesString(R.string.hl_radio_cls_confirm));
    }

    private void enableSysAudio() {
        SPUtils.setSysAudioEnable(getActivity(), mBinding.cbAudio.isChecked());
    }

    private void clsExit() {
        showProgress(R.string.hl_main_progress_exit);
        cls();
        HlThreadPoolManager.getInstance().execut("exit", new Runnable() {
            @Override
            public void run() {
                OemApplication.getApplication().doOnDestroy();
            }
        });
    }

    private void saveEditData() {
//        RadioManager.getInstance().saveBaseInf(HlApplication.getApplication());
        RadioManager.getInstance().getRadioData().saveRadioBaseInf();
    }

    private void updateVer() {
        PackageManager packageManager = requireActivity().getPackageManager();
        try {
            PackageInfo pi = packageManager.getPackageInfo(requireActivity().getPackageName(), 0);
            mBinding.tvVersionV.setText(pi.versionName);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
    }


}
